package org.fast.cms.validation.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.fast.cms.common.enums.DictEnum;
import org.fast.cms.common.utils.SpringUtils;
import org.fast.cms.service.common.DictService;
import org.fast.cms.validation.anno.DictExists;

public class DictExistsValodator implements ConstraintValidator<DictExists, Integer> {
	
	private DictEnum dictType;

	@Override
	public void initialize(DictExists constraintAnnotation) {
		dictType = constraintAnnotation.dictType();
	}

	@Override
	public boolean isValid(Integer value, ConstraintValidatorContext context) {
		if (value == null) return true;

		boolean result = false;
		DictService service = SpringUtils.getBean(DictService.class);
		try {
			result =  service.isDictExists(dictType, value);
		} catch (RuntimeException ex) {
			return false;
		}
		return result;
	}

}